package com.nercel.dsj.gksales.service.impl;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;

import com.google.gson.JsonArray;
import com.nercel.dsj.gksales.exception.ResponseCode;
import com.nercel.dsj.gksales.exception.RestApiException;
import com.nercel.dsj.gksales.service.SmsService;
import com.nercel.dsj.gksales.util.AliSmsUtil;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author qinshuangxi
 * @date 2020-06-12 使用阿里云的短信服务重新实现发短信的系列接口
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Configuration
public class SmsAliyunServiceImpl implements SmsService {

    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AliSmsUtil aliSmsUtil;

    @Value("${aliyun.sms.templateCode.verificationCode}")
    private String verificationCode; // 您的短信验证码为${code}，请完成验证，10分钟内有效，请勿泄漏于他人！

    @Value("${aliyun.sms.templateCode.vipCreated}")
    private String vipCreated; // 您的VIP帐号(${phone})已开通！

    @Value("${aliyun.sms.templateCode.agentRegistered}")
    private String agentRegistered; // 下级代理商(${phone})提交了注册信息，请注意审核！

    @Value("${aliyun.sms.templateCode.toosDefaultPWD}")
    private String toosDefaultPWD; // 营销工具默认登录密码${password}

    @Value("${aliyun.sms.templateCode.createVIPAndNotifyPWD}")
    private String createVIPAndNotifyPWD; // VIP帐户已开通，密码${password}

    @Value("${aliyun.sms.templateCode.createAccountAndNotifyPWD}")
    private String createAccountAndNotifyPWD; // 帐号已开通，密码${password}。

    @Value("${aliyun.sms.templateCode.createVipAndRelogin}")
    private String createVipAndRelogin; // 您的VIP帐号${phone}已开通，请重新登录！

    @Value("${aliyun.sms.templateCode.createActivationCode}")
    private String createActivationCode; // 您的激活码为：${code}，请妥善保管您的激活码！

    @Override
    public String sendVerificationCode(String phoneNumber) {
	String code = getRandomCode();
	String message = "{\"code\":\"" + code + "\"}";
	aliSmsUtil.sendSms(phoneNumber, verificationCode, message);
	return code;
    }

    @Override
    public String sendMessage(String phoneNumber, String message) {
	if (phoneNumber.startsWith("10")) {
	    log.info("测试短信：{}，{}", phoneNumber, message);
	    return null;
	}
	return null;
    }

    @Override
    public void sendAgentRegisteredMessage(String phoneNumber, String phone) {
	log.info("调用阿里云的接口实现，phoneNumber{}，phone{}", phoneNumber, phone);
	String message = "{\"phone\":\"" + phone + "\"}";
	aliSmsUtil.sendSms(phoneNumber, agentRegistered, message);
    }

    @Override
    public void smsVipCreatedTemplate(String phoneNumber) {
	String message = "{\"phone\":\"" + phoneNumber + "\"}";
	aliSmsUtil.sendSms(phoneNumber, vipCreated, message);
    }

    @Override
    public boolean checkSmsVCode(String phone, String vcode) {
	String smsPhoneValKey = "sms_phone_" + phone;
	String code = stringRedisTemplate.opsForValue().get(smsPhoneValKey);
	if (StringUtils.isEmpty(code)) {
	    throw new RestApiException(ResponseCode.INVALID_SMS_CODE);
	}
	if (!vcode.equals(code)) {
	    throw new RestApiException(ResponseCode.WRONG_SMS_CODE);
	}
	stringRedisTemplate.delete(smsPhoneValKey);
	return true;
    }

    @Override
    public void sendNewUserPwd(Map<String, String> data) {
	data.put("keyword", "password");
	mutilSend(toosDefaultPWD, data);
    }

    @Override
    public String mutilSend(String project, Map<String, String> data) {
	String keyword = data.get("keyword");
	Assert.notNull(keyword, "模板变量属性不能为空！");
	data.remove("keyword", keyword);
	JsonArray jsonPhone = new JsonArray();
	JsonArray jsonParam = new JsonArray();
	if (data != null) {
	    data.forEach((k, v) -> {
		jsonPhone.add(k);
		jsonParam.add("{\"" + keyword + "\":\"" + v + "\"}");
	    });
	    aliSmsUtil.sendBatchSms(project, jsonPhone.toString(), jsonParam.toString());
	}
	return null;
    }

    private static String getRandomCode() {
	int intFlag = (int) (Math.random() * 1000000);
	String flag = String.valueOf(intFlag);
	if (flag.length() == 6 && flag.substring(0, 1).equals("9")) {
	    System.out.println(intFlag);
	} else {
	    intFlag = intFlag + 100000;
	}
	return String.valueOf(intFlag);
    }

    @Override
    public void sendActivationCode(String phoneNumber, String activationCode) {
	String message = "{\"code\":\"" + activationCode + "\"}";
	aliSmsUtil.sendSms(phoneNumber, createActivationCode, message);
    }
}
